package base.junit;

import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.hyou.common.util.json.JsonUtil;

/**
 * 基础测试接口
 * 
 * @author HyouSeki
 * @version 1.0.0 2018-12-21 16:08:57 初始创建
 */
public interface BaseTester {
    
    Logger log = LoggerFactory.getLogger(BaseTester.class);
    
    default void post(MockMvc mvc, String apiUri, BaseTesterCallBack callback) {
        post(mvc, apiUri, null, callback);
    }
    
    /**
     * Post请求
     * 
     * @param mvc MockMvc
     * @param apiUri 请求RUL
     * @param form 请求表单
     * @param callback 回调
     */
    default void post(MockMvc mvc, String apiUri, Object form, BaseTesterCallBack callback) {
        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(apiUri)
                .contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON_UTF8);
        
        if (form != null) {
            String paramsJsonStr = JsonUtil.toJSONString(form);
            requestBuilder = requestBuilder.content(paramsJsonStr);
        }
        
        try {
            MvcResult result = mvc.perform(requestBuilder).andReturn();
            MockHttpServletResponse response = result.getResponse();
            String resCont = response.getContentAsString();
            
            log.info("resCont = {}", resCont);
            Assert.assertNotNull(resCont);
            
            callback.callback(resCont);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            Assert.fail("异常：" + e.getMessage());
        }
    }
    
}
